<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="规格名称" prop="name">
        <el-input
          v-model="queryParams.name"
          placeholder="请输入规格名称"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="规格状态" prop="status">
        <el-select v-model="queryParams.status" placeholder="请选择规格状态" clearable>
          <el-option
            v-for="dict in dict.type.sys_normal_disable"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['product:rule:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['product:rule:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['product:rule:remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['product:rule:export']"
        >导出</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="ruleList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="ID" align="center" prop="id" />
      <el-table-column label="规格名称" align="center" prop="name" />
      <el-table-column label="规格类型" align="ruleType" prop="ruleType">
        <!-- slot-scope="scope" 是作用域插槽，可以访问当前行的数据-->
        <template slot-scope="scope">
          <!-- scope.row 表示当前行的数据对象（即 rowsList 中的每个 obj）
              scope.row.ruleType 就是 obj.ruleType（即 <p>内存</p><p>颜色</p>）
          -->
          <div v-html="scope.row.ruleType"></div>
        </template>
      </el-table-column>
      <el-table-column label="类型属性" align="ruleTypeVal" prop="ruleTypeVal">
        <template slot-scope="scope">
          <div v-html="scope.row.ruleTypeVal"></div>
        </template>
      </el-table-column>
      <el-table-column label="规格状态" align="center" prop="status">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.sys_normal_disable" :value="scope.row.status"/>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['product:rule:edit']"
          >修改</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['product:rule:remove']"
          >删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改商品规格对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="70%" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="规格名称" prop="name">
          <el-input v-model="form.name" placeholder="请输入规格名称" />
        </el-form-item>

        <el-form-item>
          <div class="ruleAttrDiv" v-for="(ruleInfo,index) in ruleInfoList">
            <!-- 标签类型-->
            <div>
              <el-tag
                closable
                :disable-transitions="false"
                effect="dark"
                @close="handleCloseType(index)">
                {{ ruleInfo.ruleType }}
              </el-tag>
            </div>
            <!-- 标签属性-->
            <div>
              <el-tag
                :key="ruleAttr"
                closable
                effect="dark"
                type="success"
                :disable-transitions="false"
                @close="handleClose(ruleAttr,ruleInfo.ruleAttrList)" v-for="ruleAttr in ruleInfo.ruleAttrList">
                {{ ruleAttr }}
              </el-tag>
            </div>
          </div>
          <!--按钮和表格-->
          <div style="margin: 10px 0;">
            <el-button type="primary" v-show="ruleAttrStatus.addRuleAttrButton"
            @click="ruleAttrStatus.addRuleAttrButton = false;ruleAttrStatus.addRuleAttrForm = true" plain>
              添加规格
            </el-button>

            <el-form :rules="ruleAttrInfoRules" ref="ruleAttrForm"
              :inline="true" :model="ruleAttrInfo"
               v-show="ruleAttrStatus.addRuleAttrForm" class="demo-form-inline">
              <el-form-item label="规格类型" prop="ruleType">
                <el-input v-model="ruleAttrInfo.ruleType" placeholder="规格类型"></el-input>
              </el-form-item>
              <el-form-item label="类型属性" prop="ruleAttr">
                <el-input v-model="ruleAttrInfo.ruleAttr" placeholder="类型属性"></el-input>
              </el-form-item>
              <el-form-item>
                <el-button type="primary" @click="submitRuleAttr">添加</el-button>
              </el-form-item>
            </el-form>
          </div>
        </el-form-item>
        <el-form-item label="规格状态" prop="status">
          <el-radio-group v-model="form.status">
            <el-radio
              v-for="dict in dict.type.sys_normal_disable"
              :key="dict.value"
              :label="dict.value"
            >{{dict.label}}</el-radio>
          </el-radio-group>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listRule, getRule, delRule, addRule, updateRule } from "@/api/product/rule"
import index from "vuex";

export default {
  name: "Rule",
  computed: {
    index() {
      return index
    }
  },
  dicts: ['sys_normal_disable'],
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 商品规格表格数据
      ruleList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        name: null,
        status: null,
      },
      // 表单参数
      form: {},
      //规格类型和属性校验
      ruleAttrInfoRules:{
        ruleType: [
          { required: true, message: "规格名称不能为空", trigger: "blur" }
        ],
        ruleAttr: [
          { required: true, message: "规格属性不能为空", trigger: "blur" }
        ]
      },
      // 表单校验
      rules: {
        name: [
          { required: true, message: "规格名称不能为空", trigger: "blur" }
        ],
        status: [
          { required: true, message: "规格状态不能为空", trigger: "change" }
        ],
        createBy: [
          { required: true, message: "创建人不能为空", trigger: "blur" }
        ],
        createTime: [
          { required: true, message: "创建时间不能为空", trigger: "blur" }
        ],
      },
      //规格详情列表
      ruleInfoList:[

      ],
      //添加弹框的字段
      ruleAttrInfo:{
        "ruleType":null,
        "ruleAttr":null
      },
      //规格添加组件是否展示集合
      ruleAttrStatus:{
        //添加按钮
        addRuleAttrButton: true,
        //添加表单
        addRuleAttrForm: false
      }
    }
  },
  created() {
    this.getList()
  },
  methods: {
    //规格属性添加
    submitRuleAttr(){
      this.$refs['ruleAttrForm'].validate((valid) => {
        if(valid){
          //实现步骤:
          // 1.定义变量isRuleInfoIndex，初始值-1，没有规格类型则值为-1，有规格类型，索引大于-1
          let isRuleInfoIndex = -1
          // 2.遍历ruleInfoList集合，取出每个对象ruleInfo和索引index
          this.ruleInfoList.forEach((ruleInfo,index)=>{
            // 3.判断从集合取出的ruleInfo对象的属性ruleType是否等于新添加的ruleAttrInfo对象的ruleType
            if(ruleInfo.ruleType === this.ruleAttrInfo.ruleType){
              // 4.如果相等说明规格类型已经存在了将取出的索引index赋值给isRuleInfoIndex并结束箭头函数
              isRuleInfoIndex = index
              //结束箭头函数
              return
            }
          })
          // 5.判断isRuleInfoIndex的值是否等于-1，说明ruleInfoList都遍历完了还没找到，那就是没有，则向ruleInfoList集合添加
          if(isRuleInfoIndex === -1){
            //添加
            this.ruleInfoList.push(
              {
                "ruleType":this.ruleAttrInfo.ruleType,
                "ruleAttrList":[this.ruleAttrInfo.ruleAttr]
              }
            )
            ///重置
            this.resetRuleAttrInfo();
            //显示添加规格按钮
            this.showRuleAttrButton();
          }else {
            // 8.如果isRuleInfoIndex的值不等于-1，
            // 说明ruleInfoList已经存在新添加的规格类型，取出集合ruleInfoList中的规格类型对象
            //这个意思就是当你的类型存在,你要开始判断给他的属性进行添加了
            let ruleInfo = this.ruleInfoList[isRuleInfoIndex];
            // 9.使用ruleInfo.ruleAttrList调用indexOf函数，
            // 参数是ruleAttrInfo.ruleAttr，返回isRuleAttrIndex
            let isRuleAttrIndex = ruleInfo.ruleAttrList.indexOf(this.ruleAttrInfo.ruleAttr);
            // 10.如果isRuleAttrIndex 的值等于-1，
            if(isRuleAttrIndex === -1){
              //说明新添加属性不存在，则放入规格属性集合中
              ruleInfo.ruleAttrList.push(this.ruleAttrInfo.ruleAttr)
              // 11.ruleAttrInfo的属性重置为null,显示添加规格按钮并隐藏表单
              ///重置
              this.resetRuleAttrInfo();
              //显示添加规格按钮
              this.showRuleAttrButton();
            }else {
              // 如果isRuleAttrIndex 不等于-1，说明新添加属性存在，则提示错误信息
              this.$message({
                message: '规格类型【'+this.ruleAttrInfo.ruleType+'】下的规格属性' +
                  '【'+this.ruleAttrInfo.ruleAttr+'】已经存在咯',
                type: 'warning'
              });
            }
          }
        }
      });
    },
    //
    resetRuleAttrInfo(){
      // 6.重置即执行resetRuleAttrInfo函数
      this.ruleAttrInfo={
        "ruleType":null,
        "ruleAttr":null
      }
    },
    showRuleAttrButton(){
      // 7.显示添加规格按钮隐藏表单
      //显示添加规格按钮
      this.ruleAttrStatus.addRuleAttrButton = true
      //隐藏表单
      this.ruleAttrStatus.addRuleAttrForm = false
    },
    // 删除整个规则类型
    handleCloseType(ruleIndex) {
      this.ruleInfoList.splice(ruleIndex, 1);
    },
    //下面那个多的
    handleClose (ruleAttr,ruleAttrArr) {
      ruleAttrArr.splice(ruleAttrArr.indexOf(ruleAttr), 1)
    },
    /** 查询商品规格列表 */
    getList() {
      this.loading = true
      listRule(this.queryParams).then(response => {
          //将前端数据进行转换并显示到列表上
          // 内裤 [{颜色:红色}{装饰:蝴蝶结}]
          // 内裤 颜色 红色
          //     装饰 蝴蝶结 这种格式,所以咱要将数组进行一个格式转换
          //让他能以这种形式展现出来
          let rowsList = response.data.rows
          rowsList.forEach((obj)=>{
            //其实要转换的是规格属性
            let ruleInfoAttrList = JSON.parse(obj.ruleAttr);
            let ruleTypeHtml = ''
            let ruleTypeValHtml = ''
            ruleInfoAttrList.forEach(({ruleType,ruleAttrList})=>{
              ruleTypeHtml += "<p>" + ruleType + "<p>";
              ruleTypeValHtml += "<p>" + ruleAttrList.toString() + "<p>";
            })
            //给obj里的对象赋值
            obj.ruleType = ruleTypeHtml;
            obj.ruleTypeVal = ruleTypeValHtml;
          })
        this.ruleList = rowsList
        this.total = response.data.total
        this.loading = false
        })
    },
    // 取消按钮
    cancel() {
      this.open = false
      this.reset()
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        name: null,
        ruleAttr: null,
        status: null,
        revision: null,
        createBy: null,
        createTime: null,
        updateBy: null,
        updateTime: null
      }
      this.resetForm("form")
      //置空规格详情列表
      this.ruleInfoList = []
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1
      this.getList()
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm")
      this.handleQuery()
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset()
      this.open = true
      this.title = "添加商品规格"
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset()
      const id = row.id || this.ids
      getRule(id).then(response => {
        this.form = response.data
        this.open = true
        this.title = "修改商品规格"
        this.ruleInfoList = JSON.parse(response.data.ruleAttr);
      })
    },
    /** 提交按钮 */
    submitForm() {

      this.$refs["form"].validate(valid => {
        this.form.ruleAttr = JSON.stringify(this.ruleInfoList)
        if (valid) {
          if (this.form.id != null) {
            updateRule(this.form).then(response => {
              this.$modal.msgSuccess("修改成功")
              this.open = false
              this.getList()
            })
          } else {
            addRule(this.form).then(response => {
              this.$modal.msgSuccess("新增成功")
              this.open = false
              this.getList()
            })
          }
        }
      })
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids
      this.$modal.confirm('是否确认删除商品规格编号为"' + ids + '"的数据项？').then(function() {
        return delRule(ids)
      }).then(() => {
        this.getList()
        this.$modal.msgSuccess("删除成功")
      }).catch(() => {})
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('product/rule/export', {
        ...this.queryParams
      }, `rule_${new Date().getTime()}.xlsx`)
    }
  }
}
</script>

<style>
.ruleAttrDiv{
  border-bottom: solid 1px #bebebe;
  padding: 10px 0px;
}

.el-tag + .el-tag {
  margin-left: 10px;
}
.button-new-tag {
  margin-left: 10px;
  height: 32px;
  line-height: 30px;
  padding-top: 0;
  padding-bottom: 0;
}
.input-new-tag {
  width: 90px;
  margin-left: 10px;
  vertical-align: bottom;
}
</style>
